<template>
  <div class="map-container" :style="{ width: containerWidth, height: containerHeight }">
    <div :id="id" class="map" />
  </div>
</template>
<script>
/* eslint-disable no-undef */
import load from '../Tinymce/dynamicLoadScript';
const mapUrl =
  'https://webapi.amap.com/maps?v=1.4.15&key=340ec97504bc5658e4477be154e6c32d';
export default {
  name: 'AMap',
  props: {
    id: {
      type: String,
      default: function() {
        return 'AMap-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '');
      }
    },
    width: {
      type: [Number, String],
      default: 1000
    },
    height: {
      type: [Number, String],
      default: 700
    }
  },
  data() {
    return {
      map: null,
      marker: null,
      mapAddress: '',
      mapAddressComponent: {},
      mapPosition: {}
    };
  },
  computed: {
    containerWidth() {
      return this.calcSize(this.width);
    },
    containerHeight() {
      return this.calcSize(this.height);
    }
  },
  // created() {
  //   this.init();
  // },
  methods: {
    init() {
      load(mapUrl, err => {
        if (err) {
          this.$message.error(err.message);
          return;
        }
        this.initMap();
      });
    },
    initMap() {
      const mapOptions = {
        resizeEnable: true,
        zoom: 13 // 级别
      };
      this.map = new AMap.Map(this.id, mapOptions);
      this.geolocation(this.map);
      this.clickEvent(this.map);
    },
    // 搜索框
    searchOverlay(map, lnglat) {
      AMap.plugin('AMap.AdvancedInfoWindow', () => {
        const searchOverlayWindow = new AMap.AdvancedInfoWindow({
          asOrigin: false,
          asDestination: false,
          autoMove: true,
          anchor: 'top-center',
          offset: new AMap.Pixel(0, 10)
        });
        searchOverlayWindow.open(map, lnglat);
      });
    },
    // 定位
    geolocation(map) {
      const vm = this;

      AMap.plugin('AMap.Geolocation', () => {
        var geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000,
          // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
          buttonOffset: new AMap.Pixel(10, 20),
          //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          zoomToAccuracy: true,
          //  定位按钮的排放位置,  RB表示右下
          buttonPosition: 'RB',
          showButton: true
        });

        map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', onComplete);
        AMap.event.addListener(geolocation, 'error', onError);

        function onComplete(data) {
          // data是具体的定位信息
          // console.log(vm);
          vm.mapAddress = data.formattedAddress;
          vm.mapAddressComponent = data.addressComponent;
          vm.mapPosition = data.position;

          vm.searchOverlay(vm.map, data.position);
        }

        function onError(data) {
          // 定位出错
        }
      });
    },
    // 经纬度转地址
    regeoCode(map, lnglat) {
      const geocoder = new AMap.Geocoder({
        // city: "010", //城市设为北京，默认：“全国”
        radius: 10000 // 范围，默认：500
      });

      geocoder.getAddress(lnglat, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          this.mapAddressComponent = result.regeocode.addressComponent;
          this.mapAddress = result.regeocode.formattedAddress;

          this.$emit('mapClick', [this.mapAddress, this.mapAddressComponent, this.mapPosition]);
        } else {
          log.error('根据经纬度查询地址失败');
        }
      });
    },
    // 实例化点标记
    addMarker(lnglat) {
      // 创建一个 Icon
      const defaultIcon = new AMap.Icon({
        // 图标尺寸
        size: new AMap.Size(53, 68),
        // 图标的取图地址
        image:
          '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
        // 图标所用图片大小
        imageSize: new AMap.Size(26, 34),
        // 图标取图偏移量
        imageOffset: new AMap.Pixel(13, 30)
      });
      this.marker = new AMap.Marker({
        icon: defaultIcon,
        position: lnglat,
        // anchor: 'center',
        offset: new AMap.Pixel(-25, -57)
      });
      this.marker.setMap(this.map);
    },
    // 清除 marker
    clearMarker() {
      if (this.marker) {
        this.marker.setMap(null);
        this.marker = null;
      }
    },

    clickEvent(map) {
      // 为地图注册click事件获取鼠标点击出的经纬度坐标
      map.on('click', e => {
        this.mapPosition = e.lnglat;
        // console.log(e);
        this.clearMarker();
        this.addMarker(e.lnglat);
        this.regeoCode(this.map, e.lnglat);
      });
    },
    calcSize(size) {
      if (/^[\d]+(\.[\d]+)?$/.test(size)) {
        // matches `100`, `'100'`
        return `${size}px`;
      }
      return size;
    }
  }
};
</script>
<style lang="scss" scoped>
.map {
  width: 100%;
  height: 100%;
}
</style>
